package com.modular.query;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
public class QueryUtils {
    /**
     * 公共的查询数据库的业务，去掉重复的数据
     *
     * @param list
     * @param params
     * @param builder
     * @param <T>
     * @param <Q>
     * @return
     */
    public static <T, Q> List<T> excuteQuery(List<Q> list, Map<String, Object> params, QueryBuilder<T, Q> builder) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        list = list.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 如果大于最大可查询的数据
        if (list.size() > BatchQuery.MAX_QUERY_LEN) {
            return splitQuery(list, params, builder);
        } else {
            List<T> tempList = builder.excute(list, params);
            return ObjectUtil.isNull(tempList) ? new ArrayList<>() : tempList;
        }
    }

    /**
     * 公共的查询数据库的业务，去掉重复的数据
     *
     * @param list
     * @param builder
     * @param <T>
     * @param <Q>
     * @return
     */
    public static <T, Q> List<T> excuteQuery(List<Q> list, QueryBuilder<T, Q> builder) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        list = list.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 如果大于最大可查询的数据
        if (list.size() > BatchQuery.MAX_QUERY_LEN) {
            return splitQuery(list, null, builder);
        } else {
            List<T> tempList = builder.excute(list, null);
            return ObjectUtil.isNull(tempList) ? new ArrayList<>() : tempList;
        }
    }

    private static <T, Q> List<T> splitQuery(List<Q> list, Map<String, Object> params, QueryBuilder<T, Q> builder) {
        List<T> allList = new ArrayList<>();
        List<T> tempList = null;
        List<List<Q>> splitList = CollUtil.split(list, BatchQuery.MAX_QUERY_LEN);
        for (List<Q> itemList : splitList) {
            tempList = builder.excute(itemList, params);
            if (CollUtil.isNotEmpty(tempList)) {
                allList.addAll(tempList);
            }
        }
        return allList;
    }
}
